package com.jnu.keepaccounts;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.keepaccounts.data.Data;
import com.jnu.keepaccounts.data.DataBank;
import com.jnu.keepaccounts.data.DataTiaoMu;
import com.jnu.keepaccounts.data.DataTou;
import com.jnu.keepaccounts.data.XuanKa;
import com.jnu.keepaccounts.data.XuanKaBank;
import com.jnu.keepaccounts.history.History;
import com.jnu.keepaccounts.manage.Manage;
import com.jnu.keepaccounts.record.Tab;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    public MyAdapter myAdapter;
    private ArrayList<Data> datas;
    private DataBank dataBank;
    private XuanKaBank xuanKaBank;
    private ArrayList<XuanKa> xuanKas;
    private double month_shouru_in,month_shouru_out;
    private double month_zhichu_in,month_zhichu_out;
    private double net_assets;
    private static double yusuan=0;
    public void delete(DataTiaoMu dataTiaoMu){
        int flag = 0;
        int position = 0;
        int year = dataTiaoMu.getYear();
        int month = dataTiaoMu.getMonth();
        int day = dataTiaoMu.getDay();
        for(Data data:datas){
            if(data.getYear()==year&&data.getMonth()==month&&data.getDay()==day&&data.getFlag()==2){
                ((DataTou)data).cal(dataTiaoMu,-1);
                position= datas.indexOf(data);
                if(((DataTou)data).getShou()==0&&((DataTou)data).getZhi()==0) {
                    flag = 1;
                }
                break;
            }
        }
        if(flag==1)datas.remove(position);
        datas.remove(dataTiaoMu);
        set();
        dataBank.saveData();
        myAdapter.notifyDataSetChanged();
    }
    public void Add(DataTiaoMu dataTiaoMu){
        int flag = 0;
        int position = 0 ;
        DataTou dataTou = null;
        if(datas!=null){
            for(Data data1:datas){
                if(data1.getFlag()==2){
                    int tem_year = ((DataTou)data1).getYear();
                    int tem_month =((DataTou)data1).getMonth();
                    int tem_day = ((DataTou)data1).getDay();
                    if(tem_day==dataTiaoMu.getDay()&&tem_month == dataTiaoMu.getMonth()&&tem_year ==dataTiaoMu.getYear()){
                        flag =1;
                        position = datas.indexOf(data1);
                        ((DataTou) data1).cal(dataTiaoMu,1);
                        break;
                    }
                }
            }
        }
        if(flag ==1 ){
            datas.add(position+1,dataTiaoMu);
        }
        else{
            dataTou = new DataTou(2,dataTiaoMu.getYear(),dataTiaoMu.getMonth(),dataTiaoMu.getDay());
            datas.add(dataTou);
            datas.add(dataTiaoMu);
            dataTou.cal(dataTiaoMu,1);
        }

        sort();
        dataBank.saveData();
        set();
        myAdapter.notifyDataSetChanged();
    }
    ActivityResultLauncher<Intent> launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            if(data ==null)return;
            else{
            int position = data.getIntExtra("position",0);
            DataTiaoMu old_dataTiaoMu = (DataTiaoMu) datas.get(position);
            int year = old_dataTiaoMu.getYear();
            int month = old_dataTiaoMu.getMonth();
            int day = old_dataTiaoMu.getDay();

            String name = data.getStringExtra("Name");
            double shuE = data.getDoubleExtra("shuE",0 );
            int pictureId = data.getIntExtra("pictureId",0);
            String source = data.getStringExtra("source");
            int year1 = data.getIntExtra("year",0);
            int month1 = data.getIntExtra("month",0);
            int day1 = data.getIntExtra("day",0);
            int yusuan = data.getIntExtra("yusuan",0);
            Long date = data.getLongExtra("date",0);

            DataTiaoMu tem_dataTiaoMu  = new DataTiaoMu(1,pictureId,name,shuE,source,year1,month1,day1,yusuan,date);
            if(year==year1&&month==month1&&day==day1){
                for(Data data1:datas){
                    if(data1.getFlag()==2&&data1.getMonth()==month&&data1.getDay()==day&&data1.getYear()==year){
                        ((DataTou)data1).cal(old_dataTiaoMu,-1);
                        ((DataTou)data1).cal(tem_dataTiaoMu,1);
                        break;
                    }
                }
                datas.remove(old_dataTiaoMu);
                datas.add(position,tem_dataTiaoMu);
                dataBank.saveData();
                set();
                myAdapter.notifyDataSetChanged();
            }
            else{
                delete(old_dataTiaoMu);
                Add(tem_dataTiaoMu);
            }
        }
        }
    });
    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            DataTiaoMu tem_dataTiaoMu = null;
            DataTou dataTou = null;
            if (resultCode == 1) {
                if (data == null) {
                    return;
                }
                else{
                String name = data.getStringExtra("Name");
                double shuE = data.getDoubleExtra("shuE", 0);
                int pictureId = data.getIntExtra("pictureId", 0);
                String source = data.getStringExtra("source");
                int year = data.getIntExtra("year", 0);
                int month = data.getIntExtra("month", 0);
                int day = data.getIntExtra("day", 0);
                int yusuan = data.getIntExtra("yusuan",0);
                Long date = data.getLongExtra("date",0);
                tem_dataTiaoMu = new DataTiaoMu(1, pictureId, name, shuE, source, year, month, day,yusuan,date);
                Add(tem_dataTiaoMu);
                }
            }
        }
    });



    public void sort(){
        Object[] tem = this.datas.toArray();
        Arrays.sort(tem,(e1,e2)->{
            if(((Data)e1).getYear()>((Data)e2).getYear())return -1;
            else if(((Data)e1).getYear()==((Data)e2).getYear()) {
                if(((Data) e1).getMonth()>((Data) e2).getMonth())return -1;
                else if(((Data) e1).getMonth()==((Data) e2).getMonth()){
                    if(((Data) e1).getDay()>((Data) e2).getDay())return -1;
                    else if(((Data) e1).getDay()==((Data) e2).getDay()){
                        if(((Data) e1).getFlag()> ((Data) e2).getFlag() )return -1;
                        else if(((Data) e1).getFlag() == ((Data) e2).getFlag() )return 0;
                        else return 1;
                    }
                    else return 1;
                }
                else return 1;
            }
            else return 1;
        });
        ArrayList<Data> data = new ArrayList<>();
        this.datas.clear();
        for(Object object:tem){
            this.datas.add((Data) object);
        }
    }

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

            ObjectInputStream objectInputStream;
            try {
                objectInputStream = new ObjectInputStream(getApplicationContext().openFileInput("yusuan"));
                yusuan = (double) objectInputStream.readObject();
                objectInputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        TextView anaylist = findViewById(R.id.anaylist);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }
        initData();
        SlideMenu slideMenu = findViewById(R.id.slideMenu);
        ImageButton but_back = (ImageButton) findViewById(R.id.btn_back);
        but_back.setOnClickListener(v -> {
            slideMenu.switchMenu();
        });

        FloatingActionButton fabAdd = findViewById(R.id.floatingActionButton);
        fabAdd.setOnClickListener(view -> {
            Intent intent=new Intent(MainActivity.this, Tab.class);
            Bundle bd = new Bundle();
            bd.putParcelableArrayList("xuanKas",xuanKas);
            intent.putExtras(bd);
            launcherAdd.launch(intent);
        });

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        myAdapter = new MyAdapter(datas, this, new OnItemClickCallback<Data>() {
            @Override
            public void onClick(View view, Data data) {
                if(data.getFlag() == 1){
                    showDetails(view, (DataTiaoMu) data);
                }
                else {
                    Intent intent = new Intent(getApplicationContext(),Anaylist.class);
                    intent.putExtra("year",data.getYear());
                    intent.putExtra("month",data.getMonth());
                    intent.putExtra("day",data.getDay());
                    startActivity(intent);
                }
            }

            @Override
            public void onLongClick(View view, Data info) { }
        });
        recyclerView.setAdapter(myAdapter);

        set();
            LinearLayout linearLayout1 = findViewById(R.id.yue_or_net_assets);
            linearLayout1.setOnClickListener(v -> {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("设置本月预算");
                EditText editText = new EditText(MainActivity.this);
                editText.setInputType(EditorInfo.TYPE_CLASS_PHONE);
                builder.setView(editText);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(editText.getText()!= null){
                            yusuan = Double.parseDouble(String.valueOf(editText.getText()));
                            ObjectOutputStream objectOutputStream = null;
                            try {
                                objectOutputStream = new ObjectOutputStream(getApplicationContext().openFileOutput("yusuan",Context.MODE_PRIVATE));
                                objectOutputStream.writeObject(yusuan);
                            }  catch (IOException e) {
                                e.printStackTrace();
                            }finally {
                                try {
                                    if (objectOutputStream !=null){
                                        objectOutputStream.close();
                                    }
                                }catch (IOException e){
                                    e.printStackTrace();
                                }
                            }
                            set();
                        }
                    }
                });
                builder.show();
            });

            TextView home = findViewById(R.id.home);
            home.setOnClickListener(v -> slideMenu.switchMenu());
        LinearLayout linearLayout = findViewById(R.id.yonghu);
        linearLayout.setOnClickListener(v -> {
            Intent intent = new Intent(this,YongHu.class);
            intent.putExtra("name",((TextView)findViewById(R.id.yonghu_name)).getText());
            intent.putExtra("yiyu",((TextView)findViewById(R.id.yiyu)).getText());
            startActivity(intent);
        });
        TextView accountManage = findViewById(R.id.account_manage);
        accountManage.setOnClickListener(v -> {
            Intent intent = new Intent(this, AccountManage.class);
            startActivity(intent);
        });
        TextView history = findViewById(R.id.history);
        history.setOnClickListener(v -> {
            Intent intent = new Intent(this, History.class);
            startActivity(intent);
        });

        anaylist.setOnClickListener(v -> {
            Intent intent = new Intent(this,Anaylist.class);
            startActivity(intent);
        });
        TextView manage = findViewById(R.id.manage);
        manage.setOnClickListener(v -> {
            Intent intent = new Intent(this, Manage.class);
            intent.putExtra("xuanKas",xuanKas);
            startActivity(intent);
        });
    }

    public void showDetails(View view, DataTiaoMu dataTiaoMu){
        int position = datas.indexOf(dataTiaoMu);
        double yue=0;
        if(position>datas.size()/2){
            int size = datas.size();
            for(int i = size-1;i>=position;i--){
                if(datas.get(i).getFlag()==1){
                    yue+=((DataTiaoMu)datas.get(i)).getShuE();
                }
            }
        }
        else{
            yue = net_assets;
            for(int i = 0;i<position;i++){
                if(datas.get(i).getFlag()==1){
                    yue-=((DataTiaoMu)datas.get(i)).getShuE();
                }
            }
        }
        Intent intent = new Intent(MainActivity.this,RecordDetail.class);
        intent.putExtra("datatiaomu",dataTiaoMu);
        intent.putExtra("yue",yue);
        startActivity(intent);
    }
    public void set(){
        Calendar calendar = Calendar.getInstance();
        net_assets =month_shouru_in=month_zhichu_in=month_shouru_out = month_zhichu_out= 0;
        for(Data data:this.datas){
            if(data.getFlag()==1){
                net_assets+= ((DataTiaoMu)data).getShuE();
                net_assets+=((DataTiaoMu)data).getShuE();
                if(calendar.get(Calendar.YEAR)==data.getYear()&&(calendar.get(Calendar.MONTH)+1)==data.getMonth()&&((DataTiaoMu)data).getYusuan()==-1){
                    month_shouru_in += ((DataTiaoMu)data).getShuE();
                    month_zhichu_in += ((DataTiaoMu)data).getShuE();
                }
                else if(calendar.get(Calendar.YEAR)==data.getYear()&&(calendar.get(Calendar.MONTH)+1)==data.getMonth()&&((DataTiaoMu)data).getYusuan()==1){
                    month_shouru_out += ((DataTiaoMu)data).getShuE();
                    month_zhichu_out += ((DataTiaoMu)data).getShuE();
                }
            }
        }
        TextView text_net_assets = findViewById(R.id.net_assets);
        TextView textView = findViewById(R.id.yue_or_net);

        if(yusuan!=0) {
            textView.setText("本月预算余额");
            double yue = yusuan+month_shouru_in+month_zhichu_in;
            text_net_assets.setText(yue+"");
            if(yue<0)text_net_assets.setTextColor(this.getResources().getColor(R.color.red));
        }
        else {
            textView.setText("净资产");
            text_net_assets.setText(net_assets + "");
            if(net_assets<0)text_net_assets.setTextColor(this.getResources().getColor(R.color.red));
        }

        TextView text_month_shouru = findViewById(R.id.month_shouru);
        text_month_shouru.setText(month_shouru_in +"");
        TextView text_month_zhichu = findViewById(R.id.month_zhichu);
        text_month_zhichu.setText(Math.abs(month_zhichu_in)+"");
    }
    public void initData(){
        dataBank = new DataBank(MainActivity.this);
        this.datas = dataBank.loadData();
        sort();
        xuanKaBank = new XuanKaBank(MainActivity.this);
        this.xuanKas = xuanKaBank.loadData();
        xuanKaBank.saveData();
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>   {
        private ArrayList<Data> datas;
        private LayoutInflater inflater;
        private OnItemClickCallback callback = null;
        private int position;

        MyAdapter(ArrayList<Data> datas, Context context,OnItemClickCallback clickCallback){
            this.datas = datas;
            this.inflater = LayoutInflater.from(context);
            this.callback = clickCallback;
        }
        public int getItemViewType(int position){
            return datas.get(position).getFlag();
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            if(viewType==2)return new TouHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.tou,parent,false));
            else return new TiaoMuHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.tiaomu,parent,false));
        }

        @SuppressLint("WrongConstant")
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Data data = datas.get(position);
            if(data.getFlag()==2){
                
                DataTou dataTou = (DataTou)data;
                TouHolder touHolder = (TouHolder)holder;
                touHolder.date.setText(dataTou.getYear()+"-"+ dataTou.getMonth()+"-"+dataTou.getDay()+"");
                touHolder.shou.setText(dataTou.getShou()+"");
                touHolder.zhi.setText(Math.abs(dataTou.getZhi())+"");
                holder.itemView.setOnClickListener(v -> {
                    callback.onClick(v,datas.get(position));
                });
            }
            else if(data.getFlag() == 1){
                DataTiaoMu dataTiaoMu = (DataTiaoMu) data;
                TiaoMuHolder tiaoMuHolder = (TiaoMuHolder) holder;
                tiaoMuHolder.image.setImageResource(dataTiaoMu.getImage());
                tiaoMuHolder.xiangmu.setText(dataTiaoMu.getXiangMu());
                tiaoMuHolder.laiyuan.setText(dataTiaoMu.getLaiYuan());
                tiaoMuHolder.shue.setText(dataTiaoMu.getShuE()+"");
                if(dataTiaoMu.getYusuan() == 1){
                    tiaoMuHolder.yusuan.setVisibility(0);
                }
                else tiaoMuHolder.yusuan.setVisibility(8);
                holder.itemView.setOnClickListener(v -> {
                    callback.onClick(v,datas.get(position));
                });
            }
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }


        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
            }
        }
        public class TouHolder extends ViewHolder{
            TextView date;
            TextView shou;
            TextView zhi;

            public TouHolder(@NonNull View itemView) {
                super(itemView);
                date = (TextView) itemView.findViewById(R.id.textview_date);
                shou = (TextView) itemView.findViewById(R.id.textview_shou);
                zhi = (TextView) itemView.findViewById(R.id.textview_zhi);
            }
        }
        public class TiaoMuHolder extends ViewHolder implements View.OnCreateContextMenuListener,MenuItem.OnMenuItemClickListener{
            ImageView image,yusuan;
            TextView xiangmu,laiyuan,shue;
            public TiaoMuHolder(@NonNull View itemView) {
                super(itemView);
                image = (ImageView) itemView.findViewById(R.id.imageview);
                xiangmu = (TextView) itemView.findViewById(R.id.textview_xiangmu);
                laiyuan = (TextView) itemView.findViewById(R.id.textview_laiyuan);
                shue = (TextView) itemView.findViewById(R.id.textview_shue);
                yusuan = (ImageView) itemView.findViewById(R.id.yusuan);
                itemView.setOnCreateContextMenuListener(this);
            }

            public boolean onMenuItemClick(MenuItem item){
                int position = getAdapterPosition();
                DataTiaoMu dataTiaoMu = (DataTiaoMu) datas.get(position);
                switch (item.getItemId()){
                    case 0:
                        delete(dataTiaoMu);
                        break;
                    case 1:
                        showDetails(null,(DataTiaoMu) datas.get(position));
                        break;
                    case 2:
                        Intent intent = new Intent(MainActivity.this,Tab.class);
                        intent.putExtra("position",position);
                        intent.putExtra("xuanKas",xuanKas);
                        intent.putExtra("tiaomu",dataTiaoMu);

                        launcherEdit.launch(intent);
                    case 3:
                        myAdapter.notifyDataSetChanged();

                }
                return false;
            }
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                MenuItem menuItemDelete = menu.add(ContextMenu.NONE,0,ContextMenu.NONE,"删除");
                MenuItem menuItemShow = menu.add(ContextMenu.NONE,1,ContextMenu.NONE,"详情");
                MenuItem menuItemModify = menu.add(ContextMenu.NONE,2,ContextMenu.NONE,"修改");
                MenuItem menuItemRefresh = menu.add(ContextMenu.NONE,3,ContextMenu.NONE,"刷新");
                menuItemDelete.setOnMenuItemClickListener(this);
                menuItemShow.setOnMenuItemClickListener(this);
                menuItemModify.setOnMenuItemClickListener(this);
                menuItemRefresh.setOnMenuItemClickListener(this);
            }
        }

    }
}